import { Button, DotLoading, Modal, Popup, Space, Toast } from "antd-mobile";
import React, { useEffect, useState } from "react";
import requewt from "@/utils/requewt";
import { API, BASE_PATH } from "@/config";
import callFeedback from "@/components/common/modalFeedback";
import { Router, useRouter } from "next/router"
import { KvBrandComp } from "@/components/common";
import { signIn, useSession } from "next-auth/react";
import { useCookies } from "react-cookie";
import { checkENV2, WECHAT, HC, isValidArr, reloadSession, calcCrow, navigateTo,checkENV } from "@/utils";
import { motion } from "framer-motion";
import classNames from "classnames";
import Image from "next/image";
import { ResultComp } from "@/components/pages/prize";
import useApp from "@/stores/useApp";
import { useToolbar } from "@/components/common/toolbar/useToolbar";
import dayjs from "dayjs";
export default function () {
  const [loading, setLoading] = useState(false);
  const {data: userinfo} = useSession();
  const [cookies] = useCookies(['name']);
  const [visible, setVisible] = useState(false);
  const [status, setStatus] = useState(undefined);
  const [user, setUser] = useState(undefined);
  const [data, setData] = useState(undefined);
  const [remain, setRemain] = useState(0);
  const router = useRouter();
  const { handleShare,handleShowRule,handleHelpingHand,handleActivityTime,humanCheck } = useToolbar({
    setVisible
  })
  const updateUser = useApp(state => state.updateUser)

  const containerVar = {
    hidden: {opacity: 0},
    visible: {
      opacity: 1,
      transition: {
        delayChildren: 0.05,
        staggerChildren: 0.05,
      }
    },
    exit: {y: 50, opacity: 0},
  };

  const itemVar = {
    hidden: {y: 50, opacity: 0},
    visible: {
      y: 0,
      opacity: 1,
    },
  };

  const carVar = {
    hidden: {x: `-100%`,y:'10%', opacity: 0},
    visible: {
      x: 0,
      opacity: 1,
      transition: {
        delay: .4
      }
    },
    exit: {
      x: `100%`
    }
  };

  const qiVar = {
    hidden: {scale: 0, opacity: 0},
    visible: {
      scale: 1,
      opacity: 1,
      transition: {
        delay: .6,
        duration: 0.3
      }
    },
  };

  const itemVerticalLeftVar = {
    hidden: {x: -50, opacity: 0},
    visible: {x: 0, opacity: 1},
  };

  const itemVerticalRightVar = {
    hidden: {x: 50, opacity: 0},
    visible: {x: 0, opacity: 1},
  };

  const titleVar = {
    hidden: {x: -100, opacity: 0},
    visible: {
      x: 0,
      opacity: 1,
    },
  };

  const floatVar = {
    visible: {
      y: [0, 20, 0, -20, 0],
      rotate: [0, 2, 0, -2, 0],
      transition: {
        ease: `linear`,
        duration: 10,
        repeat: Infinity,
      }
    },
  };

  useEffect(() => {
    (async () => {
      if (!userinfo) return;
      setUser(userinfo?.user);
      console.log(userinfo,'userinfo')
      updateUser(userinfo.user)
      // await handler.fetch();
      const seen = sessionStorage.getItem('seen')
      if (userinfo.user.login_times<=1 && !seen) {
        handleShowRule()
        sessionStorage.setItem('seen',dayjs().format('YYYYMMDD'))
      }
    })()
  }, [userinfo])

  useEffect(() => {
    (async () => {
      Toast.clear();
      // await handler.check();
      // await handler.remain()
    })()

    return () => {
      Toast.clear();
      Modal.clear()
    }
  }, [])

  const handler = {
    check: async () => {
      const resp = await requewt(API.prize.check);
      console.log(`resp`, resp)
      if (resp?.error_code !== 0) {
        await Toast.clear();
        await callFeedback({title: resp?.msg || `请求失败`});
        return;
      }
      if (resp?.data === 1) {
        await handler.reward()
      }

    },
    reward: async () => {
      const resp = await requewt(API.prize.reward);
      console.log(`resp`, resp)
      if (resp?.error_code !== 0) {
        await Toast.clear();
        await callFeedback({title: resp?.msg || `请求失败`});
        return;
      }

      const m = callFeedback({
        bodyClassName: `act-feedback-modal cp-prize-result close-hidden`,
        content: <div className="inner">
          <ResultComp handler={handler} result={resp?.data} />
        </div>,
        actions: <>
          <Button shape={`rounded`} key={1}
                  className="act-btn act-btn-bevel"
                  onClick={e => m.close()}
          >
            确定
          </Button>
          {
            resp?.data?.status === 0 &&
            <Button shape={`rounded`}
                    className="act-btn act-btn-bevel"
                    onClick={e => navigateTo(`/lottery`)}
            >
              去抽奖
            </Button>
          }
        </>,
        closeOnAction: true,
        closeOnMaskClick: true,
      })
    },
    enter: async (item) => {
      // await router.push(`/game`)

      // return
      // if (!remain) {
      //   const m = callFeedback({
      //     bodyClassName: `act-feedback-modal cp-game-result close-hidden close-at-center-bottom`,
      //     content: <div className="inner">
      //       <div className="header">
      //         <img src={`${BASE_PATH}/img/game/game-result-header-fail.png`} alt="" />
      //       </div>
      //       <div className="content">
      //         <img className="img-fluid" src={`${BASE_PATH}/img/game/no-remain.png`} alt="" />
      //       </div>
      //     </div>,
      //     actions: [
      //       <Button shape={`rounded`}
      //               className="act-btn act-btn-bevel"
      //               onClick={e => {
      //                 m.close()
      //               }}
      //       >
      //         确定
      //       </Button>
      //     ]
      //   })
      //
      //   return
      // }
      const resp = await requewt(API.user.checkTime)
    //   const resp = {
    //     "data": null,
    //     "error_code": 1018,
    //     "msg": "很遗憾<br>今日奖品已发完,请明日早点来",
    //     "request": "GET /warm1118api/user/activity"
    // }
      if(resp.error_code !== 0) {
          const errorModal = callFeedback({
          hideClose: true,
          closeOnAction: false,
          closeOnMaskClick: false,
          title: <div></div>,
          content: <div  dangerouslySetInnerHTML={{__html: resp.msg||'游戏失败'}} className="text-center text-qy-bold" style={{display:'flex',alignItems:'center',fontSize:'2rem',justifyContent:'center'}}></div>,
          actions: <Button className="act-btn act-btn-bevel" onClick={async () => {
            if (resp.error_code === 1018) return errorModal.close()
            errorModal.close()
            const env = await checkENV2()
            if (env === 'mini') {
              wx?.miniProgram.navigateBack && wx?.miniProgram.navigateBack({})
          } else if (env === 'app') {
            if (window.QYApp.closePage) {
              window?.QYApp?.closePage()
            } else {
              global?.QYApp.closeView()
            }
          }
          }}>确 定</Button>
        })
        return
      }
      if (user?.is_robot) {
        setVisible(true);
        setTimeout(() => {
          HC((value) => {
            humanCheck(value, () => {
              router.push(`/game/k`)
            })
          }, item)
        }, 300)
        return
      }
      await router.push(`/game/k`)
      // if (resp.data.remain_game_num>0) {
      //   Toast.show({content: `进入中`, icon: `loading`});
      //   await router.push(`/game/k`)
      // } else {
      //   const m = callFeedback({
      //     content: <Space direction="vertical" align="center">
      //       <div>
      //         <img 
      //           src={`${BASE_PATH}/img/game/game-over-icon.png`}
      //           width='110'
      //         />
      //       </div>
      //       <div>
      //       您的今日任务已完成,请明日再来
      //       </div>
      //     </Space>,
      //     actions:<Button className="act-btn act-btn-bevel" onClick={()=> {
      //         m.close()
      //         // handleShare()
      //         // callback()
      //     }}>确定</Button>,
      //     hideClose:true
      // })
      // }

      
      // window.location.href = `/game/k`
    },
    remain: async () => {
      setLoading(true);
      const resp = await requewt(API.game.remain);
      setTimeout(() => setLoading(false), 300);
      if (resp?.error_code !== 0) {
        await callFeedback({title: resp?.msg || `请求失败`});
        return;
      }
      setRemain(resp?.data);
    },
    humanCheck: async (values, record) => {
      if (!values) return;
      const options = {
        method: `POST`,
        headers: {"Content-Type": `multipart/form-data`},
        body: {captchaVerifyParam:values}
      }
      const resp = await requewt(API.user.check, options);
      if (resp?.error_code !== 0 || resp?.[`msg`] !== `ok`) {
        await callFeedback({
          title: <div></div>,
          content: <div dangerouslySetInnerHTML={{__html:resp?.msg || `验证失败`}} className="text-qy-bold text-center" style={{fontSize:'2rem'}}></div>,
          actions: [<Button key="confirm" className="act-btn act-btn-bevel" onClick={()=> Modal.clear()}>确 定</Button>]
        });
        setVisible(false);
        return;
      }

      const {auth} = cookies || {};
      await signIn("credentials", {
        token: auth, redirect: false,...router.query
      });

      // reloadSession()
      // window.location.href = `/game/k`

      await router.push(`/game/k`)
    }
  }

  return (
    <>
      {/* <KvBrandComp /> */}

      <div className="deco-wrapper">
      <div style={{
            position: 'absolute',
            left: '50%',
            top: '30%',
            transform: 'translateX(-50%)',
            textAlign: 'center',
            color: '#fff'
        
      }}>
            <div style={{fontWeight:'bold'}}>
              活动时间
            </div>
            <div>
              3月8日-3月17日
            </div>
          </div>
        {/* <motion.div className="kv-header-wrapper"
                    variants={containerVar}
                    initial="hidden"
                    animate="visible"
                    exit="exit"
        >
          <motion.img variants={titleVar} initial={`hidden`}
                      animate={`visible`} src={`${BASE_PATH}/img/kv/kv-title.png`}
                      className="kv kv-title" alt="" />
        </motion.div> */}
        {/* <motion.img src={`${BASE_PATH}/img/game/landing-icon4.png`}
                      alt="deco-cloud-b-l"
                      width="134"
                      className="deco deco-icon4"
                      style={{right:'0'}}
                      variants={floatVar}
          />
        <motion.div className="inner"
                    variants={containerVar}
                    initial="hidden"
                    animate="visible"
                    exit="exit"
        >
          <motion.img src={`${BASE_PATH}/img/game/uni.png`}
                      alt="deco-cloud-b-l"
                      className="deco deco-car"
                      variants={carVar}
          />
          <motion.img src={`${BASE_PATH}/img/game/landing-icon1.png`}
                      alt="deco-cloud-b-l"
                      width="25"
                      className="deco deco-icon4"
                      style={{left:'6vw',top: 'calc(50% + -29vh)'}}
                      variants={floatVar}
          />
          <motion.img src={`${BASE_PATH}/img/game/landing-icon2.png`}
                      alt="deco-cloud-b-l"
                      width="26"
                      className="deco deco-icon4"
                      style={{top:'calc(50% - 17vh)',left:'49vw'}}
                      variants={floatVar}
          />
          <motion.img src={`${BASE_PATH}/img/game/landing-icon3.png`}
                      alt="deco-cloud-b-l"
                      width="29"
                      className="deco deco-icon4"
                      style={{right:'10vw',top:'10vh'}}
                      variants={floatVar}
          />
        </motion.div> */}


      </div>

      <div className="landing-footer">
        <div className="inner">
          
          <Button className={`act-btn act-btn-bevel`}  onClick={e => handler.enter()}>
            <span id="btn">接收专属宠爱</span>
            
          </Button>
          {/* <Button className={`act-btn act-btn-bevel`}  onClick={handleHelpingHand}>
          助力好友
            
          </Button> */}
          {/* <Button className={`act-btn act-btn-bevel`}  onClick={() => {
            handleWheel().then((resp) => {
              handleShowWheelPrize(resp?.money)
            }).catch(() => {
              handleShowWheelPrize(500)
            })
          }}>
          测试抽奖
            
          </Button> */}
        </div>
      </div>


      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false)
        }}
        position='bottom'
        destroyOnClose={true}
      >
        <div className="human-check">
          <div className="title">安全验证</div>
          <div className="loading">
          
          <span style={{fontSize:'18px'}}>加载中</span><DotLoading color="#00b578" />
          </div>
          <div id="nc" >
            
          </div>
        </div>
      </Popup>

    </>
  )
}